import React from 'react'
import { PieChart, Pie, Tooltip, Cell, ResponsiveContainer } from 'recharts'
import { NameValueLength } from '@/types/sun'

interface PieProps {
  data: NameValueLength[]
  title: string
  title2?: string
  tag?: string
  height?: string
  sum?: boolean
  count?: boolean
}

export default function PieChar({
  data,
  title,
  title2,
  tag = 'Count',
  height = '500px',
  sum = false,
  count = false
}: PieProps) {
  const numberFormatter = new Intl.NumberFormat('en-US')

  let finalTitle = title
  if (sum) {
    const totalLength = data.reduce((acc, item) => acc + item.value, 0)
    finalTitle = `${title} (${totalLength.toLocaleString()})`
  } else {
    finalTitle = `${title} (${data.length})`
  }
  if (count) {
    const totalLength = data.reduce((acc, item) => acc + item.length!, 0)
    finalTitle = `${title} (${totalLength})`
  }
  if (title2) {
    const totalLength = data.reduce((acc, item) => acc + item.value, 0)
    finalTitle = `${finalTitle} - ${title2}: ${totalLength.toLocaleString()}`
  }

  const chartData = data.map((item) => ({
    name: item.name,
    value: item.value,
    length: item.length
  }))

  return (
    <div
      style={{
        minHeight: height,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'flex-start' // Changed from 'center' to 'flex-start'
      }}
    >
      <h3 style={{ fontSize: '16px' }}>{finalTitle}</h3>{' '}
      {/* Adjusted font size */}
      <ResponsiveContainer width="100%" height={400}>
        <PieChart>
          <Pie
            data={chartData}
            dataKey="value"
            nameKey="name"
            label={({ name }) => name}
          >
            {chartData.map((entry, index) => (
              <Cell
                key={`cell-${index}`}
                fill={`hsl(${index * 72}, 30%, 60%)`}
              />
            ))}
          </Pie>
          <Tooltip
            formatter={(value, name, props) => {
              const formattedValue = numberFormatter.format(value as number)
              const length =
                props.payload.length !== undefined && props.payload.length !== 0
                  ? `${props.payload.length} 人`
                  : ''
              return [`${tag}: ${formattedValue}`, `${name} ${length}`]
            }}
          />
        </PieChart>
      </ResponsiveContainer>
    </div>
  )
}
